/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * @author 品讯科技
 */
package com.px.pa.modulars.circle.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.px.pa.constants.*;
import com.px.pa.modulars.circle.entity.*;
import com.px.pa.modulars.circle.mapper.CircleActivityMapper;
import com.px.pa.modulars.circle.service.*;
import com.px.pa.modulars.circle.vo.CircleActivityFindVo;
import com.px.pa.modulars.circle.vo.SignUserVo;
import com.px.pa.modulars.circle.vo.UserVo;
import com.px.pa.modulars.circle.vo.data;
import com.px.pa.modulars.upms.service.SysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author 品讯科技
 * @date 2024-08
 */
@Service
public class CircleActivityServiceImpl extends ServiceImpl<CircleActivityMapper, CircleActivity> implements CircleActivityService {

    @Resource
    private CircleActivityMapper circleActivityMapper;
    @Resource
    private CircleActivityService circleActivityService;

    @Resource
    private CircleActivitySignService circleActivitySignService;
    @Resource
    private CircleUserService circleUserService;
    @Resource
    private CircleActivityProgressService circleActivityProgressService;
    @Resource
    private ScopeBusinessService scopeBusinessService;
    @Resource
    private SysUserService sysUserService;

    @Resource
    private CircleNoticeService circleNoticeService;
    @Resource
    private CircleOrganizationalService organizationalService;

    @Override
    public Page<CircleActivity> getListPage(Page page, CircleActivityFindVo vo) {
        return circleActivityMapper.getListPage(page, vo);
    }

    @Override
    public Map<String, Object> getConclusion(Integer aid) {
        Map<String, Object> map = new HashMap<>();
        //活动详情
        CircleActivity circleActivity = circleActivityService.getById(aid);
        map.put("circleActivity", circleActivity);
        //活动发起人
        CircleUser circleUser = circleUserService.getById(circleActivity.getUid());
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(circleUser, userVo, true);
        map.put("userVo", userVo);
        //活动参与人数
        int activityPeopleNum = circleActivitySignService.count(new QueryWrapper<CircleActivitySign>()
                .eq("activity_id", circleActivity.getId())
                .ne("is_cancel", 1));
        map.put("activityPeopleNum", activityPeopleNum);

        //活动签到人数
        int activityIsSigninPeopleNum = circleActivitySignService.count(new QueryWrapper<CircleActivitySign>()
                .eq("activity_id", circleActivity.getId())
                .eq("is_signin",1)
                .ne("is_cancel", 1));
        map.put("activityIsSigninPeopleNum", activityIsSigninPeopleNum);

        //互动直播人数
        List<CircleActivityProgress> circleActivityProgressList1 = circleActivityProgressService.list(new QueryWrapper<CircleActivityProgress>()
                .eq("activity", circleActivity.getId()).groupBy("uid"));
        map.put("livePeopleNum", circleActivityProgressList1.size());
        //活动访问人数
        map.put("views", circleActivity.getViews());
        List<CircleActivitySign> circleActivitySignList = circleActivitySignService.list(new QueryWrapper<CircleActivitySign>()
                .eq("activity_id", circleActivity.getId())
                .ne("is_cancel", 1));
        List<Integer> userList = new ArrayList<>();
        circleActivitySignList.forEach(a -> {
            userList.add(a.getUserId());
        });
        //参与活动男生数
        int manNum = circleUserService.count(new QueryWrapper<CircleUser>().eq("sex", 1).in("id", userList).isNotNull("sex"));
        map.put("manNum", manNum);
        //参与活动女生数
        int girlNum = circleUserService.count(new QueryWrapper<CircleUser>().eq("sex", 2).in("id", userList).isNotNull("sex"));
        map.put("girlNum", girlNum);

        //共同的兴趣爱好
        List<ScopeBusiness> scopeBusinessList = scopeBusinessService.list();
        List<data> dataList = new ArrayList<>();
        scopeBusinessList.forEach(a -> {
            data data = new data();
            int count = circleUserService.count(new QueryWrapper<CircleUser>().like("manage_range", "," + a.getId() + ",").in("id", userList));
            System.out.println(a.getName());
            System.out.println(count);
            data.setName(a.getName());
            data.setNum(count);
            dataList.add(data);
        });
        //集合按照某字段排序
        Collections.sort(dataList, (o1, o2) -> {
            int result = o1.getNum().compareTo(o2.getNum());
            return result;
        });
        Collections.reverse(dataList);
        map.put("dataList", dataList);
        //图文直播
        Page<CircleActivityProgress> circleActivityProgressPage = circleActivityProgressService.page(new Page(1, 4), new QueryWrapper<CircleActivityProgress>().eq("activity", circleActivity.getId()).orderByDesc("create_time"));
        map.put("circleActivityProgressList", circleActivityProgressPage.getRecords());


        return map;
    }

    @Override
    public Integer getListCount(CircleActivityFindVo vo) {
        return baseMapper.getListCount(vo);
    }

    @Override
    public List<CircleActivity> getdbList(Page page, Integer userId) {

        Page<CircleActivitySign> signPage = circleActivitySignService.page(page,new QueryWrapper<CircleActivitySign>()
                .eq("user_id",userId)
                .ne("is_cancel",1)
                .orderByDesc("create_time"));

        List<CircleActivity> circleActivityList = new ArrayList<>();
        signPage.getRecords().forEach(a->{
            CircleActivity  activity = baseMapper.getdbList(a.getActivityId());
            if (activity !=null && activity.getClose() != 1){
                circleActivityList.add(activity);
            }
        });

        return ProcessTheData(userId,circleActivityList);
    }

    @Override
    public List<CircleActivity> ProcessTheData1(List<CircleActivity> list) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        list.forEach(a -> {
            int count1 = circleActivitySignService.count(new QueryWrapper<CircleActivitySign>()
                    .eq("activity_id", a.getId())
                    .ne("is_cancel",1));


            a.setActivityTimes(dateTimeFormatter.format(a.getActivityStartTime()) + "-" + dateTimeFormatter.format(a.getActivityEndTime()));
            a.setSignTimes(dateTimeFormatter.format(a.getSignStartTime()) + "-" + dateTimeFormatter.format(a.getSignEndTime()));
            a.setSignUpNum(count1);
            List<SignUserVo> signUserVoList = new ArrayList<>();
            Page<CircleActivitySign> circleActivitySignList = circleActivitySignService.page(new Page(1,2),
                    new QueryWrapper<CircleActivitySign>()
                            .eq("activity_id", a.getId())
                            .ne("is_cancel",1));


            circleActivitySignList.getRecords().forEach(b->{
                CircleUser circleUser = circleUserService.getById(b.getUserId());
                if (circleUser !=null && circleUser.getIsDel() == 2){
                    circleUser.setHeadPic(CancellationUser.headImg);
                    circleUser.setName(CancellationUser.headImg);
                }

                SignUserVo signUserVo = new SignUserVo();
                BeanUtil.copyProperties(circleUser,signUserVo,true);
                signUserVoList.add(signUserVo);
            });
            a.setSignUserVoList(signUserVoList);

            if (a.getIsNumberLimit().equals(IsNumberLimitEnum.IS_NUMBER_LIMIT_ENUM_ONE.getValue())) {
                int count = circleActivitySignService.count(new QueryWrapper<CircleActivitySign>()
                        .eq("activity_id", a.getId())
                        .ne("is_cancel",1));
                a.setSignNum((a.getPeopleNum()+a.getOutsidersNum()) - count);
                if ((a.getPeopleNum()+a.getOutsidersNum()) > count) {
                    a.setStatus(SignStatusEnum.SIGN_STATUS_ENUM_TWO.getValue());

                }else {
                    a.setStatus(SignStatusEnum.SIGN_STATUS_ENUM_ONE.getValue());
                    a.setSginStatus(SignStatusEnum.SIGN_STATUS_ENUM_ONE.getValue());  //报名已满状态
                }
            }
            //我的报名状态

                a.setIsSignMySelf(IsSignMySelfEnum.IS_SIGN_MY_SELF_ENUM_ONE.getValue());
            //活动的报名状态
            Date date = new Date();
            Date date1 = Date.from(a.getSignStartTime().atZone(ZoneId.systemDefault()).toInstant());
            Date date2 = Date.from(a.getSignEndTime().atZone(ZoneId.systemDefault()).toInstant());
            if (date.compareTo(date1) == -1) {
                a.setActivityStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_ONE.getValue());
            } else if (date.compareTo(date2) == 1) {
                a.setActivityStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_THREE.getValue());
            } else if (date.compareTo(date1) == 1 & date.compareTo(date2) == -1) {
                a.setActivityStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_TWO.getValue());
            }
            //活动状态
            Date dateS = Date.from(a.getActivityStartTime().atZone(ZoneId.systemDefault()).toInstant());
            Date dateE = Date.from(a.getActivityEndTime().atZone(ZoneId.systemDefault()).toInstant());
            if (date.compareTo(dateS) == -1) {
                a.setActivityRunStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_ONE.getValue());
            } else if (date.compareTo(dateE) == 1) {
                a.setActivityRunStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_THREE.getValue());
            } else if (date.compareTo(dateS) == 1 & date.compareTo(dateE) == -1) {
                a.setActivityRunStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_TWO.getValue());
            }
        });

        return list;
    }



    @Override
    public List<CircleActivity> ProcessTheData(Integer uid, List<CircleActivity> list) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        list.forEach(a -> {

            //用户的身份
            if(uid!=null&&uid.equals(a.getUid())){
                a.setIdentity(IdentityEnum.IDENTITY_ENUM_ONE.getValue());
            }
            int num =  circleActivitySignService.count(new QueryWrapper<CircleActivitySign>()
                    .eq("activity_id", a.getId())
                    .eq("user_id",uid)
                    .ne("is_cancel",1));
            if(num == 0){
                a.setIdentity(IdentityEnum.IDENTITY_ENUM_THREE.getValue());
            }else {
                a.setIdentity(IdentityEnum.IDENTITY_ENUM_TWO.getValue());
            }

            int count1 = circleActivitySignService.count(new QueryWrapper<CircleActivitySign>()
                    .eq("activity_id", a.getId())
                    .ne("is_cancel",1));


            a.setActivityTimes(dateTimeFormatter.format(a.getActivityStartTime()) + "-" + dateTimeFormatter.format(a.getActivityEndTime()));
            a.setSignTimes(dateTimeFormatter.format(a.getSignStartTime()) + "-" + dateTimeFormatter.format(a.getSignEndTime()));
            a.setSignUpNum(count1);
            List<SignUserVo> signUserVoList = new ArrayList<>();
            Page<CircleActivitySign> circleActivitySignList = circleActivitySignService.page(new Page(1,2),
                    new QueryWrapper<CircleActivitySign>()
                            .eq("activity_id", a.getId())
                            .ne("is_cancel",1));


            circleActivitySignList.getRecords().forEach(b->{
                CircleUser circleUser =   circleUserService.getById(b.getUserId());

                //已注销用户

                if (circleUser !=null && circleUser.getIsDel() == 2){
                    circleUser.setHeadPic(CancellationUser.headImg);
                    circleUser.setName(CancellationUser.headImg);
                }

                SignUserVo signUserVo = new SignUserVo();
                BeanUtil.copyProperties(circleUser,signUserVo,true);
                signUserVoList.add(signUserVo);
            });
            a.setSignUserVoList(signUserVoList);

            if (a.getIsNumberLimit().equals(IsNumberLimitEnum.IS_NUMBER_LIMIT_ENUM_ONE.getValue())) {
                int count = circleActivitySignService.count(new QueryWrapper<CircleActivitySign>()
                        .eq("activity_id", a.getId())
                        .ne("is_cancel",1));
                a.setSignNum((a.getPeopleNum()+a.getOutsidersNum()) - count);
                if ((a.getPeopleNum()+a.getOutsidersNum()) > count) {
                    a.setStatus(SignStatusEnum.SIGN_STATUS_ENUM_TWO.getValue());

                }else {
                    a.setStatus(SignStatusEnum.SIGN_STATUS_ENUM_ONE.getValue());
                    a.setSginStatus(SignStatusEnum.SIGN_STATUS_ENUM_ONE.getValue());  //报名已满状态
                }
            }
            //我的报名状态
            int n = circleActivitySignService.count(new QueryWrapper<CircleActivitySign>()
                    .eq("user_id", uid)
                    .eq("activity_id", a.getId())
                    .ne("is_cancel",1));
            if (n == 0) {
                a.setIsSignMySelf(IsSignMySelfEnum.IS_SIGN_MY_SELF_ENUM_ONE.getValue());
            } else {
                a.setIsSignMySelf(IsSignMySelfEnum.IS_SIGN_MY_SELF_ENUM_TWO.getValue());
            }

            //如果取消过报名
            CircleActivitySign circleActivitySign = circleActivitySignService.getOne(new QueryWrapper<CircleActivitySign>()
                    .eq("activity_id",a.getId())
                    .eq("user_id",uid));

            if (circleActivitySign!=null){
                Integer isOk  = circleActivitySign.getIsCancel();
                if (isOk == null){
                    isOk = -1;
                }

                if (isOk == 1){
                    a.setIsSignMySelf(IsSignMySelfEnum.IS_SIGN_MY_SELF_ENUM_THREE.getValue());
                }
            }




            //活动的报名状态
            Date date = new Date();
            Date date1 = Date.from(a.getSignStartTime().atZone(ZoneId.systemDefault()).toInstant());
            Date date2 = Date.from(a.getSignEndTime().atZone(ZoneId.systemDefault()).toInstant());
            if (date.compareTo(date1) == -1) {
                a.setActivityStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_ONE.getValue());
            } else if (date.compareTo(date2) == 1) {
                a.setActivityStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_THREE.getValue());
            } else if (date.compareTo(date1) == 1 & date.compareTo(date2) == -1) {
                a.setActivityStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_TWO.getValue());
            }
            //活动状态
            Date dateS = Date.from(a.getActivityStartTime().atZone(ZoneId.systemDefault()).toInstant());
            Date dateE = Date.from(a.getActivityEndTime().atZone(ZoneId.systemDefault()).toInstant());
            if (date.compareTo(dateS) == -1) {
                a.setActivityRunStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_ONE.getValue());
            } else if (date.compareTo(dateE) == 1) {
                a.setActivityRunStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_THREE.getValue());
            } else if (date.compareTo(dateS) == 1 & date.compareTo(dateE) == -1) {
                a.setActivityRunStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_TWO.getValue());
            }
            if(StrUtil.isEmpty(a.getOrganize())){
                CircleUser u=circleUserService.getById(a.getUid());
                if(u!=null){
                    a.setUserName(u.getName());
                    if(u.getOrganizationalId()!=null){
                        CircleOrganizational o=organizationalService.getById(u.getOrganizationalId());
                        if(o!=null){
                            a.setOrganize(o.getName());
                        }
                    }
                }
            }
        });

        return list;
    }

    @Override
    public List<CircleActivity> getAcitivyByDelUser(Integer uid) {
        return baseMapper.getAcitivyByDelUser(uid);
    }

    @Override
    public Map<String, Object> getMap(Map<String, Object> map, Integer uid,String tenant) {
        Page page = new Page(1, 3);
        CircleActivityFindVo vo = new CircleActivityFindVo();
        LocalDateTime now = LocalDateTime.now();
        //查询近7日创建的人员 并拿出头像
        Page<CircleUser> users = circleUserService.page(page, new QueryWrapper<CircleUser>()
                .ne("is_tourists", IsTouristsEnum.IS_TOURISTS_ENUM_TWO.getValue())
                .isNotNull("organizational_id")
                .eq("tenant_code",tenant)
                .eq("is_del",1)
                .between("create_time", now.minusDays(7), now)
                .orderByDesc("create_time"));
        //新同事
        map.put("newColleagues", users.getRecords());
        Integer count = circleUserService.count(new QueryWrapper<CircleUser>()
                .isNotNull("organizational_id")
                .eq("tenant_code",tenant)
                .eq("is_del",1)
                .ne("is_tourists", IsTouristsEnum.IS_TOURISTS_ENUM_TWO.getValue()));
        //总数量
        map.put("count", count);
        Page<CircleNotice> noticeList = circleNoticeService.page(page, new QueryWrapper<CircleNotice>()
                .eq("tenant_code",tenant)
                .orderByDesc("create_time"));
        //翻滚公告
        map.put("noticeList", noticeList.getRecords());
        List<CircleActivity> returnEntity = new ArrayList<>();
        //进行中活动
        vo.setType(2);
        vo.setAudit(1);
        vo.setTenant(tenant);
        Page<CircleActivity> ongoing = circleActivityService.getListPage(page, vo);
        ongoing.getRecords().forEach(a -> {
            returnEntity.add(a);
        });
        //未开始活动
        vo.setType(1);
        Page<CircleActivity> notAtThe = circleActivityService.getListPage(page, vo);
        notAtThe.getRecords().forEach(b -> {
            returnEntity.add(b);
        });
        //推荐活动
        map.put("recommended", circleActivityService.ProcessTheData(uid,returnEntity));
        //活动代办
        Page activityPage = new Page(1, 20);
        List<CircleActivity> circleActivityPage = circleActivityService.getdbList(activityPage, uid);
        map.put("dbActivity", circleActivityPage);
        return map;
    }
}
